from datetime import datetime
import time as time_module
from sqlalchemy import delete, select, update, func
from sqlalchemy.ext.asyncio import AsyncSession
from module_admin.entity.do.machine_do import BaMachine
from module_admin.entity.vo.machine_vo import MachinePageQueryModel
from module_admin.entity.vo.machine_vo import MachineModel
from utils.page_util import PageUtil
from utils.log_util import logger

class MachineDao:
    """
    机台管理模块数据库操作层
    """

    @classmethod
    async def get_machine_list(
        cls, db: AsyncSession, query_object: MachinePageQueryModel, data_scope_sql: str, is_page: bool = False
    ):
        """
        根据查询参数获取机台列表信息

        :param db: orm对象
        :param query_object: 查询参数对象
        :param data_scope_sql: 数据权限对应的查询sql语句
        :param is_page: 是否开启分页
        :return: 用户列表信息对象
        """
        
        query = (
            select(BaMachine)
            .where(
                BaMachine.machine_name.like(f'%{query_object.machine_name}%') if query_object.machine_name else True,
                BaMachine.machine_id == query_object.machine_id if query_object.machine_id else True,
                BaMachine.status == query_object.status if query_object.status is not None else True,
                BaMachine.create_time.between(
                    int(time_module.mktime(datetime.strptime(query_object.begin_time, '%Y-%m-%d').timetuple())),
                    int(time_module.mktime(datetime.strptime(query_object.end_time, '%Y-%m-%d').timetuple())) + 86399
                )
                if query_object.begin_time and query_object.end_time
                else True
            )
            .order_by(BaMachine.id)
            .distinct()
        )
        machine_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
        
        # logger.info(f'query_object: {query_object}')
        # compiled_query = query.compile(compile_kwargs={"literal_binds": True})
        # logger.info(f'compiled_query: {str(compiled_query)}')
        # logger.info(f'machine_list: {machine_list}')
        
        return machine_list

    @classmethod
    async def get_detail_by_id(cls, db: AsyncSession, id: int):
        """
        根据id获取详细信息

        :param db: orm对象
        :param id: id
        :return: 信息对象
        """
        detail = (await db.execute(select(BaMachine).where(BaMachine.id == id))).scalars().first()

        return detail
    
    @classmethod
    async def add_dao(cls, db: AsyncSession, addModel: MachinePageQueryModel):
        """
        新增数据库操作

        :param db: orm对象
        :param addModel: 新增对象
        :return:
        """
        db_result = BaMachine(**addModel.model_dump())
        db.add(db_result)
        await db.flush()

        return db_result
    
    @classmethod
    async def edit_dao(cls, db: AsyncSession, editModel: dict):
        """
        编辑字典类型数据库操作

        :param db: orm对象
        :param editModel: 需要更新的字典类型字典
        :return:
        """
        logger.info(f'editModel: {editModel}')
        await db.execute(update(BaMachine), [editModel])

    @classmethod
    async def delete_dao(cls, db: AsyncSession, deleteModel: BaMachine):
        """
        删除用户数据库操作

        :param db: orm对象
        :param user: 用户对象
        :return:
        """
        await db.execute(
            delete(BaMachine)
            .where(BaMachine.id == deleteModel.id)
        )
    
    @classmethod
    async def get_machine_select_list(cls, db: AsyncSession, machine_info: MachineModel, data_scope_sql: str):
        """
        获取所有机台列表信息

        :param db: orm对象
        :param machine_info: 机台对象
        :param data_scope_sql: 数据权限对应的查询sql语句
        :return: 机台列表信息
        """
        search_list_result = (
            (
                await db.execute(
                    select(
                        func.concat(BaMachine.machine_id, '-', BaMachine.machine_name).label('machine_info'),
                        BaMachine.id
                    )
                    .distinct()
                )
            )
            .all()
        )
        
        # 将结果转换为字典列表
        search_list_result = [{'machine_info': row.machine_info, 'id': row.id} for row in search_list_result]

        # query = (select(
        #                 func.concat(BaMachine.machine_id, '-', BaMachine.machine_name).label('machine_info'),
        #                 BaMachine.id
        #             ).distinct())
        # compiled_query = query.compile(compile_kwargs={"literal_binds": True})
        # logger.info(f'compiled_query: {str(compiled_query)}')
        # logger.info(f'search_list_result: {search_list_result}')

        return search_list_result